/*
 * Copyright (c) 2025 Industrial Software Feature Database
 */
package com.comac.ins.isfd.util;

import org.springframework.core.io.ByteArrayResource;

import java.io.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

public class CreateGltfFromBDF {
    // todo: 解析bdf文件，返回解析后bdf、gltf、以及json文件
    public static Map createGltfFromBDF(String bdfPath, String materialPath,
                                        String parsedBdfPath, String gltfPath,
                                        String xrefPath) {

        // 创建JSON格式字符串
        String jsonString = "{\n" +
            "  \"" + "bdf_path" + "\": \"" + bdfPath + "\",\n" +
            "  \"" + "material_path" + "\": \"" + materialPath + "\",\n" +
            "  \"" + "parsed_bdf_path" + "\": \"" + parsedBdfPath + "\",\n" +
            "  \"" + "gltf_path" + "\": \"" + gltfPath + "\",\n" +
            "  \"" + "xref_path" + "\": \"" + xrefPath + "\"\n" +
            "}";
        return PythonExecute.excute("create_gltf_from_bdf",jsonString);
        //return executePython(jsonString);
    }

    public static Map getBDFStats(String bdfPath, String materialPath){
        String jsonString = "{\n" +
            "  \"" + "bdf_path" + "\": \"" + bdfPath + "\",\n" +
            "  \"" + "material_path" + "\": \"" + materialPath + "\"\n" +
            "}";

        return PythonExecute.excute("parse_bdf_stats",jsonString);
    }


    // 执行python代码， 返回gltf路径
    public static Map executePython(String jsonString) {
        System.out.println("假装python运行, \n jsonString = " + jsonString);
        Map<String, String> resultMap = new HashMap<>();

        // 添加键值对 "运行结果" -> "成功"
        resultMap.put("运行结果", "成功");
        return resultMap;
    }


    public static void main(String[] args) throws IOException {

        String bdfPath = "C:\\Users\\lijpt\\Desktop\\ceshi\\cargodoor.bdf";
        String gltfPath = "C:\\Users\\lijpt\\Desktop\\ceshi\\gltf\\cargodoor.gltf";
        String xrefPath = "C:\\Users\\lijpt\\Desktop\\ceshi\\xref\\cargodoor.json";
        String binPath = "C:\\Users\\lijpt\\Desktop\\ceshi\\gltf\\cargodoor.bin";
        String materialPath = "C:\\Users\\lijpt\\Desktop\\ceshi\\C919_Material_Library.bdf";
        String parsedBdfPath = "C:\\Users\\lijpt\\Desktop\\ceshi\\parsed_bdf\\cargodoor.json";
        Map parsingResult = createGltfFromBDF(bdfPath, materialPath, parsedBdfPath, gltfPath, xrefPath);
        System.out.println(parsingResult);
        List<String> filePaths = new ArrayList<>();
        filePaths.add(gltfPath);
        filePaths.add(binPath);
        filePaths.add(xrefPath);
        byte[] zippedFiles = findAndZipFiles(filePaths);
        ByteArrayResource resource = new ByteArrayResource(zippedFiles);

        try {
            String filePath = replaceExtension(bdfPath, ".zip");; // 目标文件路径
            saveByteArrayResourceAsZip(resource, filePath);
            System.out.println("File saved successfully.");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private static String replaceExtension(String filePath, String newExtension) {
        int dotIndex = filePath.lastIndexOf('.');
        if (dotIndex != -1) {
            return filePath.substring(0, dotIndex) + newExtension;
        } else {
            return filePath + newExtension;
        }
    }

    /**
     * 根据文件路径列表查找文件，并将这些文件打包为一个压缩文件
     *
     * @param filePaths 要查找的文件路径列表
     * @return 压缩文件的字节数组
     * @throws IOException 如果在文件操作或压缩过程中发生错误
     */
    private static byte[] findAndZipFiles(List<String> filePaths) throws IOException {
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        boolean filesFound = false;

        try (ZipOutputStream zos = new ZipOutputStream(bos)) {
            for (String path : filePaths) {
                File file = new File(path);
                if (file.exists() && file.isFile()) {
                    addToZipFile(file, zos);
                    filesFound = true;
                } else {
                    System.err.println("File not found: " + path);
                }
            }

            if (!filesFound) {
                throw new FileNotFoundException("No files found to zip.");
            }

            zos.finish();
        }

        return bos.toByteArray();
    }

    /**
     * 将单个文件添加到压缩包中
     *
     * @param file 要添加的文件
     * @param zos  ZipOutputStream实例
     * @throws IOException 如果在文件读取或压缩过程中发生错误
     */
    private static void addToZipFile(File file, ZipOutputStream zos) throws IOException {
        try (FileInputStream fis = new FileInputStream(file)) {
            ZipEntry zipEntry = new ZipEntry(file.getName());
            zos.putNextEntry(zipEntry);

            byte[] bytes = new byte[1024];
            int length;
            while ((length = fis.read(bytes)) >= 0) {
                zos.write(bytes, 0, length);
            }

            zos.closeEntry();
        }
    }

    public static void saveByteArrayResourceAsZip(ByteArrayResource resource, String filePath) throws IOException {
        try (OutputStream outputStream = new FileOutputStream(filePath)) {
            // 将 ByteArrayResource 的内容写入到指定的文件路径
            outputStream.write(resource.getByteArray());
        }
    }


}
